<template>
  <el-row :gutter="10">
    <el-col :span="10" :xs="24">
      <ContentWrap class="h-1/1">
        <ArticleDetailSimpleList @row-click="handleArticleDetailSimpleListRowClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="14" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户类型" prop="userType">
            <el-select
              v-model="queryParams.userType"
              placeholder="请选择用户类型"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.USER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户昵称" prop="userNickname">
            <el-input
              v-model="queryParams.userNickname"
              placeholder="请输入用户昵称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="评论状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择评论状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态" prop="approveStatus">
            <el-select
              v-model="queryParams.approveStatus"
              placeholder="请选择审核状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="IP" prop="creatorIp">
            <el-input
              v-model="queryParams.creatorIp"
              placeholder="请输入创建者ip"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="区域" prop="creatorCity">
            <el-input
              v-model="queryParams.creatorCity"
              placeholder="请输入创建者城市"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" />
              重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['cms:app-site-comment:create']"
              v-if="queryParams.appSiteId && queryParams.appId"
            >
              <Icon icon="ep:plus" class="mr-5px" />
              新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['cms:app-site-comment:export']"
            >
              <Icon icon="ep:download" class="mr-5px" />
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
          @cell-click="listTableCellClickHandler"
        >
          <el-table-column label="编号" align="center" prop="id" />
          <el-table-column label="用户类型" align="center" prop="userType">
            <template #default="scope">
              <dict-tag
                :type="DICT_TYPE.USER_TYPE"
                :value="scope.row.userType"
                @click="listTableCellClickHandler(scope.row, '')"
              />
            </template>
          </el-table-column>
          <el-table-column label="用户昵称" align="center" prop="userNickname" />
          <el-table-column label="内容" align="center" prop="commentContent" />
          <el-table-column label="状态[点击修改]" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="审核[点击修改]" align="center" prop="approveStatus">
            <template #default="scope">
              <dict-tag
                :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS"
                :value="scope.row.approveStatus"
              />
            </template>
          </el-table-column>
          <el-table-column label="区域" align="center" prop="creatorCity" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="操作" align="center" fixed width="150">
            <template #default="scope">
              <el-button
                link
                type="success"
                @click="openForm('reply', scope.row.id)"
                v-hasPermi="['cms:app-site-comment:update']"
              >
                回复
              </el-button>
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['cms:app-site-comment:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['cms:app-site-comment:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>
  <!-- 表单弹窗：添加/修改 -->
  <AppSiteCommentForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AppSiteCommentApi, AppSiteCommentVO } from '@/api/cms/appsitecomment'
import AppSiteCommentForm from './AppSiteCommentForm.vue'
import ArticleDetailSimpleList from '@/views/cms/articledetail/ArticleDetailSimpleList.vue'
import { ref } from 'vue'
import { ArticleDetailVO } from '@/api/cms/articledetail'
import { ElMessageBox, ElSwitch } from 'element-plus'

/** 站点评论 列表 */
defineOptions({ name: 'AppSiteComment' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AppSiteCommentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userType: undefined,
  userId: undefined,
  userNickname: undefined,
  appSiteId: undefined as number | undefined,
  appId: undefined as string | undefined,
  categoryId: undefined as number | undefined,
  articleId: undefined as number | undefined,
  parentId: undefined,
  commentContent: undefined,
  status: undefined,
  approveStatus: undefined,
  creatorIp: undefined,
  creatorCity: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const curArticleDetailVO = ref<ArticleDetailVO>()
const handleArticleDetailSimpleListRowClick = async (row: ArticleDetailVO) => {
  queryParams.appSiteId = row.appSiteId
  queryParams.appId = row.appId
  queryParams.categoryId = row.categoryId
  queryParams.articleId = row.id
  curArticleDetailVO.value = row
  handleQuery()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AppSiteCommentApi.getAppSiteCommentPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, curArticleDetailVO.value, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AppSiteCommentApi.deleteAppSiteComment(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const listTableCellClickHandler = async (row: AppSiteCommentVO, column: any) => {
  if (column.property === 'status') {
    try {
      // 删除的二次确认
      await message.confirm(
        `确定${row.status === 0 ? '关闭' : '开启'}编号为【${row.id}】的评论吗？`
      )
      // 发起删除
      await AppSiteCommentApi.updateAppSiteCommentStatus({
        id: row.id,
        status: row.status === 0 ? 1 : 0
      })
      message.success(t('common.updateSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
  if (column.property === 'approveStatus' && row.approveStatus === 1) {
    try {
      const approveStatus = ref<number>(2)
      await ElMessageBox({
        title: '修改评论审核状态',
        // Should pass a function if VNode contains dynamic props
        message: () =>
          h(ElSwitch, {
            modelValue: approveStatus.value,
            activeText: '通过',
            inactiveText: '不通过',
            activeValue: 2,
            inactiveValue: 3,
            'onUpdate:modelValue': (val: boolean | string | number) => {
              approveStatus.value = val as number
            }
          })
      })
      await AppSiteCommentApi.updateAppSiteCommentApproveStatus({
        id: row.id,
        approveStatus: approveStatus.value
      } as AppSiteCommentVO)
      message.success(t('common.updateSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AppSiteCommentApi.exportAppSiteComment(queryParams)
    download.excel(data, '站点评论.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
